package com.xbongbong.saas.model.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.Arith;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.pro.constant.BusinessConstant;
import com.xbongbong.pro.enums.SaasMarkEnum;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.ParameterConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.dao.CostAdjustProductDao;
import com.xbongbong.saas.domain.entity.CostAdjustProductEntity;
import com.xbongbong.saas.enums.SelectProductEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.WarehouseEnum;
import com.xbongbong.saas.enums.product.CostAdjustProductEnum;
import com.xbongbong.saas.model.CostAdjustProductModel;
import com.xbongbong.saas.toolbox.help.FastJsonHelper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author WuHB
 * @date 2021/11/22 08:59
 */
@Service("costAdjustProductModel")
public class CostAdjustProductModelImpl implements CostAdjustProductModel {

    @Resource
    private CostAdjustProductDao costAdjustProductDao;


    /**
     * 插入
     *
     * @param entity 实体
     * @return 是否成功
     * @throws XbbException 数据库操作异常
     */
    @Override
    public Integer insert(CostAdjustProductEntity entity) throws XbbException {
        int now = DateUtil.getInt();
        entity.setAddTime(now);
        entity.setUpdateTime(now);
        return costAdjustProductDao.insert(entity);
    }

    /**
     * 更新
     *
     * @param entity 实体
     * @return 是否成功
     * @throws XbbException 数据库操作异常
     */
    @Override
    public Integer update(CostAdjustProductEntity entity) throws XbbException {
        entity.setUpdateTime(DateUtil.getInt());
        return costAdjustProductDao.update(entity);
    }

    /**
     * 获取符合查询条件的记录
     *
     * @param param 查询条件
     * @return 符合查询条件的记录
     */
    @Override
    public List<CostAdjustProductEntity> findEntitys(Map<String, Object> param) {
        return costAdjustProductDao.findEntitys(param);
    }

    /**
     * 获取符合查询条件的记录总数
     *
     * @param param 查询条件
     * @return 符合查询条件的记录总数
     */
    @Override
    public Integer getEntitysCount(Map<String, Object> param) {
        return costAdjustProductDao.getEntitysCount(param);
    }

    /**
     * Description: 查询符合条件的数据（无子表单数据）
     *
     * @param param 查询条件
     * @return java.util.List<T>
     */
    @Override
    public List<CostAdjustProductEntity> findEntitysWithoutSub(Map<String, Object> param) {
        return null;
    }

    /**
     * 批量插入
     *
     * @param productEntityList 产品集合
     */
    @Override
    public void insertBatch(List<CostAdjustProductEntity> productEntityList) {
        costAdjustProductDao.insertBatch(productEntityList);
    }

    @Override
    public JSONObject formatSingleProduct(CostAdjustProductEntity productEntity, List<PaasFormDataEntityExt> warehouseList)  throws XbbException{
        JSONObject json = Objects.isNull(productEntity.getData()) ? new JSONObject() : productEntity.getData();
        Long warehouseId = productEntity.getWarehouseId();
        Map<Long, String> warehouseNameMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        for (PaasFormDataEntityExt paasFormDataEntityExt : warehouseList) {
            JSONObject data = paasFormDataEntityExt.getData();
            warehouseNameMap.put(paasFormDataEntityExt.getId(), FastJsonHelper.getStringOrDefaultFromFormData(data, WarehouseEnum.WAREHOUSE_NAME.getAttr(), ""));
        }
        for (CostAdjustProductEnum productEnum : CostAdjustProductEnum.values()) {
            String attr = productEnum.getAttr();
            switch (productEnum) {
                case PRODUCT:
                    json.put(attr, productEntity.getProductId());
                    break;
                case WAREHOUSE:
                    JSONArray warehouseArr = packegeLinkBusinessJsonArray(warehouseId, warehouseNameMap.getOrDefault(warehouseId, ""), XbbRefTypeEnum.WAREHOUSE.getCode(), SaasMarkEnum.SAAS.getCode());
                    json.put(attr, warehouseArr);
                    break;
                case OLD_COST:
                    json.put(attr, productEntity.getOldCost());
                    break;
                case NEW_COST:
                    json.put(attr, productEntity.getNewCost());
                    break;
                case ADJUST_AMOUNT:
                    json.put(attr, productEntity.getCostAdjustAmount());
                    break;
                case TOTAL_COST:
                    json.put(attr, productEntity.getTotalCost());
                    break;
                case STOCK:
                    json.put(attr, productEntity.getInventoryNumber());
                    break;
                case BATCH:
                    json.put(attr, productEntity.getBatch());
                    break;
                case BASIC_UNIT:
                    json.put(attr, productEntity.getProductUnit());
                    break;
                case PRODUCE_DATE:
                    json.put(attr, productEntity.getProduceDate());
                    break;
                case GUARANTEE_PERIOD:
                    if (Objects.nonNull(productEntity.getGuaranteePeriod())){
                        json.put(attr, Arith.div(productEntity.getGuaranteePeriod(),86400));
                    }
                    break;
                default:
                    break;
            }
            json.put("refId", productEntity.getId());
            json.put(SelectProductEnum.UNIT_GROUP.getAttr(), productEntity.getGroupId());
            json.put(SelectProductEnum.RATE.getAttr(), productEntity.getRate());
            json.put(SelectProductEnum.BUSINESS_UNIT.getAttr(), productEntity.getBusinessUnit());
            json.put(BusinessConstant.PRODUCT_SUB_ID, productEntity.getId());
        }
        return json;
    }

    @Override
    public List<CostAdjustProductEntity> listByAdjustId(String corpid, Long costAdjustId, List<Integer> delIn) {
        Map<String, Object> param = new HashMap<>();
        param.put("corpid", corpid);
        param.put("costAdjustId", costAdjustId);
        param.put("delIn", delIn);
        param.put(ParameterConstant.ORDER_BY_STR, BasicConstant.SORT);
        return this.findEntitys(param);
    }

    @Override
    public Integer deleteBatchById(Collection<Long> idList, String corpid, Integer del) {
        if (CollectionsUtil.isEmpty(idList)) {
            return 0;
        }
        return costAdjustProductDao.deleteBatchById(idList, corpid, del);
    }

    @Override
    public Integer deleteByCostAdjustId(Long costAdjustId, String corpid) {
        return costAdjustProductDao.deleteByCostAdjustId(costAdjustId, corpid);
    }

    public JSONArray packegeLinkBusinessJsonArray(Long dataId, String name, Integer businessType, Integer saasMark) {
        JSONArray jsonArray = new JSONArray();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put(StringConstant.SAAS_LINK_BUSINESS_ID, dataId);
        jsonObject.put(StringConstant.SAAS_LINK_BUSINESS_NAME, name);
        jsonObject.put(StringConstant.BUSINESS_TYPE, businessType);
        jsonObject.put(StringConstant.SAAS_MARK, saasMark);
        jsonArray.add(jsonObject);
        return jsonArray;
    }

    @Override
    public void updateCostProductById(List <CostAdjustProductEntity> costAdjustProductEntityList, String corpid){
        costAdjustProductDao.updateCostProductById(costAdjustProductEntityList, corpid);
    }

    /**
     * 获取成本调整单产品信息
     *
     * @param corpid       公司ID
     * @param adjustIdList 调整单ID
     */
    @Override
    public List<CostAdjustProductEntity> getProductsByAdjustIdIn(String corpid, List<Long> adjustIdList) {
        Map<String, Object> param = new HashMap<>();
        param.put("del", 0);
        param.put("corpid", corpid);
        param.put("costAdjustIdIn", adjustIdList);
        return costAdjustProductDao.findEntitys(param);
    }

    /**
     * 批量跟新成本调整单产品信息
     *
     * @param costAdjustProductEntityList 成本调整单产品信息
     * @param corpid                      公司ID
     * @return 影响行数
     */
    @Override
    public Integer updateBatch(List<CostAdjustProductEntity> costAdjustProductEntityList, String corpid) {
        if (CollectionsUtil.isEmpty(costAdjustProductEntityList) || StringUtil.isEmpty(corpid)) {
            return 0;
        }
        return costAdjustProductDao.updateBatch(costAdjustProductEntityList, corpid);
    }
}
